package com.egao.common.manage.company;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.component.minio.config.MinioBucket;
import com.egao.common.component.minio.service.MinioService;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.company.constants.CompanyConstants;
import com.egao.common.module.company.constants.PreachConstants;
import com.egao.common.module.company.entity.*;
import com.egao.common.module.company.entity.vo.PreachFormVO;
import com.egao.common.module.company.entity.vo.PreachListVO;
import com.egao.common.module.company.entity.vo.PreachWorkerForm;
import com.egao.common.module.company.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;



/**
 * 单位宣讲会管理
 * @author dl
 */
@Api(tags = "单位宣讲会管理")
@RestController
@RequestMapping("${api}")
public class CompanyPreachController extends BaseController {

    @Autowired
    private PreachService preachService;
    @Autowired
    private FieldService fieldService;
    @Autowired
    private FieldRecordService fieldRecordService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private PreachWorkerService preachWorkerService;
    @Autowired
    private MinioService minioService;

    @PreAuthorize("hasAuthority('company')")
    @ApiOperation(value = "宣讲会信息", notes = "未审核状态升序 创建时间倒序")
    @OperLog(value = "宣讲会信息", desc = "分页查询宣讲会信息")
    @ApiPageParam
    @GetMapping("/company/preach/page")
    public PageResult<PreachListVO> page(HttpServletRequest request) {
        PageParam<PreachListVO> pageParam = new PageParam<>(request);
        pageParam.put("user_id", getLoginUserId());
        return new PageResult<>(preachService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "添加宣讲会信息", desc = "添加宣讲会信息", result = true)
    @ApiOperation(value = "添加宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @PostMapping("/company/preach/save")
    public JsonResult save(@Valid @RequestBody PreachFormVO preachFormVO) {
        preachFormVO.setCreateBy(getLoginUserId());
        // 设置宣讲会信息为待审核
        preachFormVO.setState(CompanyConstants.RECRUIT_STATE_DSH);
        // 单位发布
        preachFormVO.setAddType("1");
        // 参与人员待完善
        preachFormVO.setWorkerState("3");
        return preachService.savePreach(preachFormVO);
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "修改宣讲会信息", desc = "修改宣讲会信息", result = true)
    @ApiOperation(value = "修改宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @PutMapping("/company/preach/update")
    public JsonResult update(@Valid @RequestBody PreachFormVO preachFormVO) {
        return preachService.updatePreach(preachFormVO);
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "取消宣讲会信息", desc = "取消宣讲会信息", result = true)
    @ApiOperation(value = "取消宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @PutMapping("/company/preach/cancel")
    public JsonResult cancel(@Valid @RequestBody PreachFormVO preachFormVO) {
        return preachService.cancelPreach(preachFormVO);
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "删除宣讲会信息", desc = "删除宣讲会信息", result = true)
    @ApiOperation(value = "删除宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recruitFormVO", value = "recruitFormVO", required = true, dataType = "RecruitFormVO")
    })
    @PutMapping("/company/preach/delete")
    public JsonResult deletePreach(@RequestBody PreachFormVO preachFormVO) {
        return preachService.deletePreach(preachFormVO);
    }

    @PreAuthorize("hasAuthority('company')")
    @ApiOperation(value = "获取宣讲会信息详情")
    @OperLog(value = "获取宣讲会信息详情", desc = "获取宣讲会信息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "宣讲会信息id", required = true, dataType = "int")
    })
    @GetMapping("/company/preach/detail")
    public JsonResult detail(Integer id) {
        return preachService.detail(id);
    }

    @PreAuthorize("hasAuthority('company')")
    @ApiOperation(value = "验证宣讲会时间场地")
    @GetMapping("/company/preach/field")
    public JsonResult field(String date, String type) {
        int count = fieldService.count(new LambdaQueryWrapper<Field>().eq(Field::getType, "1"));
        int count1 = fieldRecordService.count(new LambdaQueryWrapper<FieldRecord>()
                .eq(FieldRecord::getStartDate, date)
                .eq(FieldRecord::getTimeType, type)
        );

        if (count > count1) {
            return JsonResult.ok();
        }

        Company company = companyService.getByUserId(getLoginUserId());
        if (company == null) {
            throw new BusinessException("单位不存在");
        }

        int count3 = fieldRecordService.count(new LambdaQueryWrapper<FieldRecord>()
                .eq(FieldRecord::getStartDate, date)
                .eq(FieldRecord::getTimeType, type)
                .eq(FieldRecord::getType, "0")
                .eq(FieldRecord::getCompanyId, company.getId())
        );
        if (count3 > 0) {
            return JsonResult.ok();
        }

        return JsonResult.error();
    }

    @PreAuthorize("hasAuthority('company')")
    @ApiOperation(value = "宣讲会参与人员集合")
    @GetMapping("/company/preach/worker")
    public JsonResult worker(Integer id) {
        Preach preach = preachService.getById(id);
        preach.setApproachedImgPreview(minioService.getPreSignedObjectUrl(MinioBucket.MINIO_PREACH, preach.getApproachedImg()));

        List<PreachWorker> list =
        preachWorkerService.list(new LambdaQueryWrapper<PreachWorker>().eq(PreachWorker::getPreachId, id).orderByAsc(PreachWorker::getId));

        PreachWorkerForm preachWorkerForm = new PreachWorkerForm();
        preachWorkerForm.setPreach(preach);
        preachWorkerForm.setPreachWorkerList(list);
        return JsonResult.ok().setData(preachWorkerForm);
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "添加参会人员", desc = "添加参会人员", result = true)
    @ApiOperation(value = "添加参会人员")
    @PostMapping("/company/preach/add-worker")
    public JsonResult addWorker(@RequestBody PreachWorker preachWorker) {
        if (preachWorkerService.save(preachWorker)) {
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "保存参与人员健康码等", desc = "保存参与人员健康码等", result = true)
    @ApiOperation(value = "保存参与人员健康码等")
    @PutMapping("/company/preach/save-worker")
    public JsonResult saveWorker(@RequestBody PreachWorkerForm preachWorkerForm) {
        Preach preach = preachWorkerForm.getPreach();
        preach.setWorkerState(PreachConstants.WORKER_STATE_WAIT_CHECK);
        preach.setCarState(PreachConstants.CAR_STATE_DONT_NEED);

        // 填写了车牌号 更改录入车牌状态
        preachWorkerForm.getPreachWorkerList().forEach(d -> {
            if (!StrUtil.isBlank(d.getCar())) {
                preach.setCarState(PreachConstants.CAR_STATE_WAIT);
            }
        });

        if (preachService.updateById(preach)) {
            preachWorkerService.updateBatchById(preachWorkerForm.getPreachWorkerList());
        }

        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "删除参与人员", desc = "删除参与人员", result = true)
    @ApiOperation(value = "删除参与人员")
    @PutMapping("/company/preach/delete-worker/{id}")
    public JsonResult deletePreachWorker(@PathVariable("id") Integer id) {
        if (preachWorkerService.removeById(id)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }
}
